﻿<%@ WebHandler Language="C#" Class="ContainerWipReport" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using ReportBusiness;

/**
 * Description: 在制批次查询报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.4.22
 **/

public class ContainerWipReport : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDetail":
                        r = getDetail(jObject);//查询明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    //查询方法
    Result getData(JObject jObject)
    {
        string sql = @"
SELECT cci.mfgordername,mfg.plannedstartdate,mfg.plannedcompletiondate,
       cci.familylistnames,cci.productname,cci.productdescription,cci.togetherflag,c.militarytype,
       NVL(MM.scrapQty,0) scrapqty,
       NVL(n.daishenQty,0) daishenqty,
       NVL(o.kaikaQty,0) kaikaqty,
       NVL(q.wipqty,0) wipqty
FROM containercurrentinfo cci
LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
LEFT JOIN container c ON c.containerid = cci.containerid
LEFT JOIN employee e ON c.startemployeeid = e.employeeid
LEFT JOIN workcenter w ON w.workcenterid = cci.fromworkcenterid
LEFT JOIN (
     SELECT cci.familylistnames,cci.productname,cci.togetherflag,SUM(csd.lossqty) scrapqty
     FROM containercurrentinfo cci
     INNER JOIN containersteprecord csd ON cci.containerid = csd.containerid
     WHERE cci.isinstore = 0 AND cci.containerstatus = 1";
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        //零件图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        //流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }
        sql += @"
     GROUP BY cci.familylistnames,cci.productname,cci.togetherflag
) MM ON cci.familylistnames = MM.familylistnames AND cci.productname = MM.productname AND cci.togetherflag = MM.togetherflag
LEFT JOIN 
(
    SELECT cci.familylistnames productfamily,cci.productname,cci.togetherflag,sum(cni.zbhgps) daishenQty
    FROM containernonconforminginfo cni
    LEFT JOIN containercurrentinfo cci on cci.containerid = cni.containerid
    WHERE cni.zsljl IS NULL ";
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        //零件图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        //流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }
        sql += @"
    GROUP BY cci.familylistnames,cci.productname,cci.togetherflag
) n ON cci.familylistnames = n.productfamily AND cci.productname = n.productname AND cci.togetherflag = n.togetherflag
LEFT JOIN 
(
  SELECT cci.familylistnames productfamily,cci.productname,cci.togetherflag,SUM(cci.qty) kaikaQty
  FROM container c
  LEFT JOIN containercurrentinfo cci ON c.containerid = cci.containerid
  WHERE 1=1 ";
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        //零件图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        //流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }
        sql += @"
  GROUP BY cci.familylistnames,cci.productname,cci.togetherflag
) o  ON cci.familylistnames = o.productfamily AND cci.productname = o.productname AND cci.togetherflag = o.togetherflag
LEFT JOIN 
(
   SELECT cci.familylistnames productfamily,cci.productname,cci.togetherflag,SUM(cci.qty) wipQty
   FROM containercurrentinfo cci
   WHERE cci.isinstore = 0 ";
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        //零件图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        //流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }
        sql += @"
   GROUP BY cci.familylistnames,cci.productname,cci.togetherflag
) q ON cci.familylistnames = q.productfamily AND cci.productname = q.productname AND cci.togetherflag = q.togetherflag
WHERE cci.isinstore =  0 AND cci.containerstatus = 1 ";
        //分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        //主制工区
        if (jObject["workcenterid"] != null && jObject["workcenterid"].ToString() != "")
        {
            sql += string.Format(" AND cci.fromworkcenterid = '{0}'", jObject["workcenterid"].ToString());
        }

        //计划员
        if (jObject["jihuayuan"] != null && jObject["jihuayuan"].ToString() != "")
        {
            sql += string.Format(" AND e.employeeid = '{0}'", jObject["jihuayuan"].ToString());
        }

        //机型
        if (jObject["productfamilyname"] != null && jObject["productfamilyname"].ToString() != "")
        {
            sql += string.Format(" AND cci.familylistnames = '{0}'", jObject["productfamilyname"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        //零件图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        //流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        //开卡时间
        if (jObject["containerstartdate"] != null && jObject["containerstartdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["containerstartdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND TRUNC(c.originalstartdate) BETWEEN TO_DATE('{0}','yyyy-mm-dd') and TO_DATE('{1}','yyyy-mm-dd')", arr[0].ToString(), arr[1].ToString());
            }
        }

        //计划完成时间
        if (jObject["plannedcompletiondate"] != null && jObject["plannedcompletiondate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["plannedcompletiondate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND TRUNC(cci.plannedcompletiondate) BETWEEN TO_DATE('{0}','yyyy-mm-dd') and TO_DATE('{1}','yyyy-mm-dd')", arr[0].ToString(), arr[1].ToString());
            }
        }

        sql += @" 
GROUP BY cci.mfgordername,mfg.plannedstartdate,mfg.plannedcompletiondate,cci.familylistnames,cci.productname,cci.productdescription,cci.togetherflag,c.militarytype,
         mm.scrapQty,n.daishenQty,o.kaikaQty,q.wipqty
ORDER BY cci.togetherflag";
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //查询批次明细
    Result getDetail(JObject jObject)
    {
        string sql = @" 
SELECT cci.mfgordername,cci.familylistnames productfamily,cci.productname,cci.fromworkcentername workcentername,e.fullname,
       cci.workflowstepname,cci.togetherflag,cci.containername,c.originalstartdate,cci.qty,c.lastactivitydate
FROM containercurrentinfo cci
LEFT JOIN container c ON cci.containerid = c.containerid
LEFT JOIN employee e ON c.startemployeeid = e.employeeid  
WHERE cci.isinstore = 0 AND cci.containerstatus = 1 ";

        //分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        //主制工区
        if (jObject["workcenterid"] != null && jObject["workcenterid"].ToString() != "")
        {
            sql += string.Format(" AND cci.fromworkcenterid = '{0}'", jObject["workcenterid"].ToString());
        }

        //计划员
        if (jObject["jihuayuan"] != null && jObject["jihuayuan"].ToString() != "")
        {
            sql += string.Format(" AND e.employeeid = '{0}'", jObject["jihuayuan"].ToString());
        }

        //机型
        if (jObject["productfamilyname"] != null && jObject["productfamilyname"].ToString() != "")
        {
            sql += string.Format(" AND cci.familylistnames = '{0}'", jObject["productfamilyname"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        //零件图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        //流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        //批次号
        if (jObject["togetherflag"] != null && jObject["togetherflag"].ToString() != "")
        {
            sql += string.Format(" AND cci.togetherflag LIKE '%{0}%'", jObject["togetherflag"].ToString());
        }

        //开卡时间
        if (jObject["containerstartdate"] != null && jObject["containerstartdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["containerstartdate"].ToString());
            sql += string.Format(" AND c.originalstartdate >= TO_DATE('{0} 00:00:00','yyyy-mm-dd hh24:mi:ss')", arr[0].ToString());
            sql += string.Format(" AND c.originalstartdate <= TO_DATE('{0} 23:59:59','yyyy-mm-dd hh24:mi:ss')", arr[1].ToString());
        }

        sql += @" ORDER BY cci.mfgordername,cci.familylistnames,cci.productname,cci.workflowstepname,
                           cci.fromworkcentername,e.fullname,cci.workflowstepname,cci.togetherflag,cci.containername";

        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = @"
SELECT cci.mfgordername,mfg.plannedstartdate,mfg.plannedcompletiondate,
       cci.familylistnames,cci.productname,cci.productdescription,cci.togetherflag,cci.containername,cci.qty,cci.workflowstepname,w.workcentername fromworkcentername,
       e.fullname,c.originalstartdate,NVL(MM.scrapQty,0) scrapQty,NVL(n.daishenQty,0) daishenQty,NVL(o.kaikaQty,0) kaikaQty,
       NVL(q.wipqty,0) wipqty,c.lastactivitydate,c.militarytype
FROM containercurrentinfo cci
LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
LEFT JOIN container c ON c.containerid = cci.containerid
LEFT JOIN employee e ON c.startemployeeid = e.employeeid
LEFT JOIN workcenter w ON w.workcenterid = cci.fromworkcenterid
LEFT JOIN 
(
  SELECT m.productfamily,m.productname,m.togetherflag,SUM(m.scrapqty) scrapqty
  FROM (
         SELECT cci.familylistnames productfamily,cci.productname,cci.togetherflag,cci.containername,qhd.qty scrapqty,
                qhd.checkdate checkvalidatedate,lr.lossreasonname
         FROM container c
         LEFT JOIN containercurrentinfo cci ON cci.containerid = c.containerid
         LEFT JOIN qtyhistorydetails qhd ON qhd.containerid = c.containerid
         LEFT JOIN lossreason lr ON qhd.reasoncodeid = lr.lossreasonid
         LEFT JOIN containerstepworkreport cst ON cst.containerstepworkreportid = qhd.containerstepworkreportid
         WHERE qhd.changeqtytype = 2 AND qhd.changecount = 1 AND c.containerid <> c.containername AND cst.containerstepworkreportid IS NOT NULL ";

        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        sql += @"
         UNION ALL 

         SELECT cci.familylistnames productfamily,cci.productname,cci.togetherflag,cci.containername,abs(cr.qty) scrapqty,
                cr.createdate checkvalidatedate,lrs.lossreasonname
         FROM CheckQtyChangeRecord cr
         LEFT JOIN containercurrentinfo cci ON cci.containerid = cr.containerid
         LEFT JOIN containerstepworkreport cwr ON cwr.containerstepworkreportid = cr.containerstepworkreportid AND cwr.isuse = 0
         LEFT JOIN lossreason lrs ON lrs.lossreasonid = cr.reasonid
         LEFT JOIN containerstepscrapinfo csc ON csc.containerid = cci.containerid
         WHERE cr.isuse = 0 AND cr.changeqtytype = 2 ";

        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        sql += @"
  ) m 
  GROUP BY m.productfamily,m.productname,m.togetherflag
) MM ON cci.familylistnames = MM.productfamily AND cci.productname = MM.productname AND cci.togetherflag = MM.togetherflag
LEFT JOIN 
(
    SELECT cci.familylistnames productfamily,cci.productname,cci.togetherflag,sum(cni.zbhgps) daishenQty
    FROM containernonconforminginfo cni
    LEFT JOIN containercurrentinfo cci on cci.containerid = cni.containerid
    WHERE cni.zsljl IS NULL
    GROUP BY cci.familylistnames,cci.productname,cci.togetherflag
) n ON cci.familylistnames = n.productfamily AND cci.productname = n.productname AND cci.togetherflag = n.togetherflag
LEFT JOIN 
(
  SELECT cci.familylistnames productfamily,cci.productname,cci.togetherflag,SUM(cci.qty) kaikaQty
  FROM container c
  LEFT JOIN containercurrentinfo cci ON c.containerid = cci.containerid
  GROUP BY cci.familylistnames,cci.productname,cci.togetherflag
) o  ON cci.familylistnames = o.productfamily AND cci.productname = o.productname AND cci.togetherflag = o.togetherflag
LEFT JOIN 
(
   SELECT cci.familylistnames productfamily,cci.productname,cci.togetherflag,SUM(cci.qty) wipQty
   FROM containercurrentinfo cci
   WHERE cci.isinstore = 0
   GROUP BY cci.familylistnames,cci.productname,cci.togetherflag
) q ON cci.familylistnames = q.productfamily AND cci.productname = q.productname AND cci.togetherflag = q.togetherflag
WHERE cci.isinstore =  0 AND cci.containerstatus = 1 
";
        //分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        //主制工区
        if (jObject["workcenterid"] != null && jObject["workcenterid"].ToString() != "")
        {
            sql += string.Format(" AND cci.fromworkcenterid = '{0}'", jObject["workcenterid"].ToString());
        }

        //计划员
        if (jObject["jihuayuan"] != null && jObject["jihuayuan"].ToString() != "")
        {
            sql += string.Format(" AND e.employeeid = '{0}'", jObject["jihuayuan"].ToString());
        }

        //机型
        if (jObject["productfamilyname"] != null && jObject["productfamilyname"].ToString() != "")
        {
            sql += string.Format(" AND cci.familylistnames = '{0}'", jObject["productfamilyname"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        //零件图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        //流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        //开卡时间
        if (jObject["containerstartdate"] != null && jObject["containerstartdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["containerstartdate"].ToString());
            sql += string.Format(" AND c.originalstartdate >= TO_DATE('{0} 00:00:00','yyyy-mm-dd hh24:mi:ss')", arr[0].ToString());
            sql += string.Format(" AND c.originalstartdate <= TO_DATE('{0} 23:59:59','yyyy-mm-dd hh24:mi:ss')", arr[1].ToString());
        }

        //计划完成时间
        if (jObject["plannedcompletiondate"] != null && jObject["plannedcompletiondate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["plannedcompletiondate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND TRUNC(cci.plannedcompletiondate) BETWEEN TO_DATE('{0}','yyyy-mm-dd') and TO_DATE('{1}','yyyy-mm-dd')", arr[0].ToString(), arr[1].ToString());
            }
        }

        DataTable dt = dal.GetDataTable(sql);

        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        dt.Columns["mfgordername"].Caption = "订单号";
        dt.Columns["familylistnames"].Caption = "机型";
        dt.Columns["productname"].Caption = "零件图号";
        dt.Columns["productdescription"].Caption = "零件名称";
        dt.Columns["togetherflag"].Caption = "批次号";
        dt.Columns["containername"].Caption = "流水卡号";
        dt.Columns["qty"].Caption = "数量";
        dt.Columns["workflowstepname"].Caption = "当前工序";
        dt.Columns["fromworkcentername"].Caption = "主制工区";
        dt.Columns["fullname"].Caption = "计划员";
        dt.Columns["originalstartdate"].Caption = "开卡日期";
        dt.Columns["kaikaQty"].Caption = "投产数";
        dt.Columns["kaikaQty"].SetOrdinal(4);
        dt.Columns["daishenQty"].Caption = "待审理数";
        dt.Columns["daishenQty"].SetOrdinal(5);
        dt.Columns["scrapQty"].Caption = "报废数";
        dt.Columns["scrapQty"].SetOrdinal(6);
        dt.Columns["wipQty"].Caption = "在制数";
        dt.Columns["wipQty"].SetOrdinal(7);
        dt.Columns["lastactivitydate"].Caption = "当前工序开始时间";
        dt.Columns["militarytype"].Caption = "军种";
        dt.Columns["plannedstartdate"].Caption = "计划开始时间";
        dt.Columns["plannedcompletiondate"].Caption = "计划完成时间";
        ExportHelper.ExportExcel(dt, "在制批次查询报表");
    }
}